<template>
  <div id="app">
    <!-- 新建任务按钮 -->
    <el-button type="success" @click="dialogVisible = true">新建任务</el-button>

    <h2>定时任务管理</h2>

    <!-- 弹出框 -->
    <div class="dialog">
      <el-dialog
        title="定时任务管理配置"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>

          <!-- 主要切换组件 -->
          <el-form-item label="任务频率" prop="Hz">
            <el-tabs
              :tab-position="tabPosition"
              style="height: 200px"
              @tab-click="getTaskMode($event)"
            >
              <el-tab-pane label="每时">
                <setHour :child="HzDate"></setHour>
              </el-tab-pane>
              <el-tab-pane label="每分">
                <setMinu></setMinu>
              </el-tab-pane>
              <el-tab-pane label="每秒">
                <setScond></setScond>
              </el-tab-pane>
              <el-tab-pane label="每天">
                <setDay></setDay>
              </el-tab-pane>
              <el-tab-pane label="每周">
                <setWeek></setWeek>
              </el-tab-pane>
              <el-tab-pane label="每月">
                <setMonth></setMonth>
              </el-tab-pane>
            </el-tabs>
          </el-form-item>

          <el-form-item label="任务类型" prop="region">
            <el-select v-model="ruleForm.region" placeholder="请选择任务类型">
              <el-option label="模型" value="模型"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="模型名" prop="desc">
            <el-input type="input" v-model="ruleForm.desc"></el-input>
          </el-form-item>

          <el-form-item label="模型参数" prop="modelParem">
            <el-input type="textarea" v-model="ruleForm.modelParem"></el-input>
          </el-form-item>

          <el-form-item label="模型账户" prop="modelUser">
            <el-input type="input" v-model="ruleForm.modelUser"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >立即创建</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>

    <!-- 表格数据 -->
    <div class="box" stripe style="width: 100%">
      <el-table :data="tableData" v-loading="loading">
        <el-table-column prop="ID" label="任务ID" width="180">
        </el-table-column>
        <el-table-column prop="name" label="任务名称" width="180">
        </el-table-column>
        <el-table-column prop="beginTime" label="任务开始时间">
        </el-table-column>
        <el-table-column prop="endTime" label="任务结束时间"> </el-table-column>
        <el-table-column prop="state" label="任务状态"> </el-table-column>
        <el-table-column prop="operation" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini">配置</el-button>
            <el-button
              type="primary"
              size="mini"
              v-show="getBtnState(scope).isPause"
              @click="pause"
              >暂停</el-button
            >
            <el-button
              type="primary"
              size="mini"
              v-show="getBtnState(scope).isContinue"
              @click="ContinueTask"
              >继续</el-button
            >
            <el-button
              type="primary"
              size="mini"
              v-show="getBtnState(scope).isEnd"
              @click="stopTask"
              >终止</el-button
            ><el-button
              type="primary"
              size="mini"
              v-show="getBtnState(scope).isReboot"
              >重新启动</el-button
            >
            <el-button
              type="primary"
              size="mini"
              v-show="getBtnState(scope).isResult"
              >查看结果</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
//引入频率组件
import setHour from "./components/setHour";
import setMinu from "./components/setMinu";
import setScond from "./components/setSecond";
import setDay from "./components/setDay";
import setWeek from "./components/setWeek";
import setMonth from "./components/setMonth";
export default {
  data: () => ({
    //布尔值
    loading: true, //表格数组加载状态
    dialogVisible: false, //新建任务弹框

    //任务列表表格数组
    tableData: [],
    taskMode: "hour", //任务频率模式

    //子组件数据
    HzDate: {
      datePick: "", //日期
      num: 1, //间隔时间
      checked: false, //是否选中
    },
    //表单数据
    tabPosition: "left",
    ruleForm: {
      name: "", //任务名称
      region: "", //任务类型
      desc: "", //任务名
      modelParem: "", //模型参数
      modelUser: "", //模型账户
    },

    //表单规则
    rules: {
      name: [
        { required: true, message: "请输入任务名称", trigger: "blur" },
        { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
      ],
      region: [
        { required: true, message: "请选择任务类型", trigger: "change" },
      ],
      date: [
        {
          type: "date",
          required: true,
          message: "请选择时间",
          trigger: "change",
        },
      ],
      desc: [{ required: true, message: "请填写模型名", trigger: "blur" }],
      modelParem: [
        { required: true, message: "请填写模型参数", trigger: "blur" },
      ],
      modelUser: [
        { required: true, message: "请填写模型账户", trigger: "blur" },
      ],
    },
  }),

  created() {
    //定时刷新任务列表
    // setInterval(() => {
    //   this.getTaskList();
    // }, 5000);
    this.getTaskList();
  },
  methods: {
    //获取任务频率
    getTaskMode($event) {
      let obj = $event.$vnode.componentOptions.propsData;
      let tabValue = Object.values(obj);
      switch (tabValue[0]) {
        case "每时":
          this.taskMode = "hour";
          break;
        case "每分":
          this.taskMode = "minute";
          break;
        case "每秒":
          this.taskMode = "second";
          break;
        case "每天":
          this.taskMode = "day";
          break;
        case "每周":
          this.taskMode = "week";
          break;
        case "每月":
          this.taskMode = "month";
          break;
      }
    },
    //获取任务列表
    async getTaskList() {
      //ajax数据
      let optype = {
        data: JSON.stringify({
          type: "getList",
        }),
      };
      let pd = this.$qs.stringify(optype);
      //发送ajax请求
      const { data, status } = await this.$http.post("api/TaskInfo.tsl", pd);
      if (status !== 200) return this.$message.error("请求错误!");
      this.loading = false;
      //添加数据到表格
      data.forEach((el) => {
        let obj = {};
        obj["ID"] = el.TASKID;
        obj["name"] = el.TASKNAME;
        obj["beginTime"] = el.TASKBDATE;
        obj["endTime"] = el.TASKEDATE;
        //翻译任务状态码
        switch (el.TASKSTATUS) {
          case -1:
            el.TASKSTATUS = "已终止";
            break;
          case 2:
            el.TASKSTATUS = "等待执行";
            break;
          case 0:
            el.TASKSTATUS = "未开始";
            break;
          case 1:
            el.TASKSTATUS = "正在执行";
            break;
          case 3:
            el.TASKSTATUS = "已完成";
            break;
          case 4:
            el.TASKSTATUS = "已暂停";
            break;
          default:
            el.TASKSTATUS = "无效状态";
        }
        obj["state"] = el.TASKSTATUS;
        this.tableData.push(obj);
      });
    },
    //用于根据状态显示操作按钮
    getBtnState(scope) {
      const state = scope.row.state;
      //布尔值 控制按钮显示
      let obj = {
        isPause: false, // 暂停按钮
        isContinue: false, //继续按钮
        isEnd: false, //终止按钮
        isReboot: false, //重启按钮
        isResult: false, //查看结果按钮
      };
      //根据任务状态决定显示的按钮
      switch (state) {
        case "已终止":
          obj.isReboot = true;
          break;
        case "等待执行":
          obj.isPause = true;
          obj.isEnd = true;
          break;
        case "未开始":
          obj.isPause = true;
          obj.isEnd = true;
          break;
        case "正在执行":
          obj.isPause = true;
          obj.isEnd = true;
          break;
        case "已完成":
          obj.isResult = true;
          obj.isEnd = true;
          break;
        case "已暂停":
          obj.isContinue = true;
          obj.isEnd = true;
          break;
      }

      return obj;
    },

    //弹框中的关闭选项
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => {});
    },
    // submitForm 和 resetForm 负责表单是否必填项验证
    //弹框中的表单提交
    submitForm(formName) {
      if (this.HzDate.datePick == "")
        return this.$message.error("开始时间日期不能为空!");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //用于传递给后台的数据
          let postData = {
            data: JSON.stringify({
              userid: "uid01",
              tasktype: "model",
              taskname: this.ruleForm.name,
              region: this.ruleForm.region,
              taskconf: JSON.stringify({
                //任务配置
                modelname: this.ruleForm.desc,
                modelParem: this.modelParem,
                modelUser: this.modelUser,
              }),
              //任务频率
              taskoftenconf: JSON.stringify({
                mode: this.taskMode,
                begtime: this.HzDate.datePick,
                interval: this.HzDate.num,
              }),
              type: "submit", // 用于后端识别接口
            }),
          };
          let pd = this.$qs.stringify(postData);
          //发送ajax请求
          this.$http.post("api/TaskInfo.tsl", pd).then((res) => {
            console.log(res);
            if (res.status !== 200) return this.$message.error("请求出错!");
            this.$message({
              message: "恭喜你，创建任务成功!",
              type: "success",
            });
          });
        } else {
          this.$message.error("错误创建!!");
          return false;
        }
      });
    },
    //暂停任务
    async pause() {
      let postData = {
        data: JSON.stringify({
          taskid: "001",
          type: "pause",
        }),
      };
      let pd = this.$qs.stringify(postData);
      await this.$http.post("api/TaskInfo.tsl", pd).then((res) => {
        if (res.status !== 200) return this.$message.error("请求出错!");
        this.$message({
          message: "任务已暂停!",
          type: "success",
        });
      });
    },
    //终止任务
    async stopTask() {
      let postData = {
        data: JSON.stringify({
          taskid: "001",
          type: "termination",
        }),
      };
      let pd = this.$qs.stringify(postData);
      await this.$http.post("api/TaskInfo.tsl", pd).then((res) => {
        if (res.status !== 200) return this.$message.error("请求出错!");
        this.$message({
          message: "任务已终止!",
          type: "success",
        });
      });
    },
    async ContinueTask() {
      let postData = {
        data: JSON.stringify({
          taskid: "001",
          type: "continue",
        }),
      };
      let pd = this.$qs.stringify(postData);
      await this.$http.post("api/TaskInfo.tsl", pd).then((res) => {
        if (res.status !== 200) return this.$message.error("请求出错!");
        this.$message({
          message: "任务已继续!",
          type: "success",
        });
      });
    },
    //查看结果
    Viewresult() {},
    //重置按钮 清空当前的所有内容
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  components: {
    setHour,
    setMinu,
    setScond,
    setDay,
    setWeek,
    setMonth,
  },
};
</script>
<style lang="less">
#app {
  .el-button--success {
    margin: 0 10px 15px 0;
    float: right;
  }
  .dialog {
    .el-dialog {
      width: 80% !important;
    }
    .el-menu-vertical-demo:not(.el-menu--collapse) {
      width: 200px;
      min-height: 400px;
    }
    .el-tabs {
      height: auto !important;
    }
  }
  .box {
    width: 100%;
    .el-button {
      margin: 2px;
    }
  }
}
</style>
